package com.baili.controller.login;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baili.dto.BaseTransferEntity;
import com.baili.dto.InsterOrganization;
import com.baili.dto.SelectUserInput;
import com.baili.dto.common.UserConstants;
import com.baili.service.user.UserService;
import com.baili.util.EhcacheUtil;
import com.baili.util.MobileConfig;
import com.baili.util.StringUtil;

@Controller
@RequestMapping(value = "")
public class UserController {

	private static Logger log = Logger.getLogger(UserController.class);
	@Autowired
	private UserService userService;
	@Autowired
	private EhcacheUtil ehcacheUtil;
	
	/**
	 * 是否注册
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/service/isRegist")
	@ResponseBody
	public BaseTransferEntity isRegist(HttpServletRequest request,
			HttpServletResponse response) {
		BaseTransferEntity baseTransferEntity = new BaseTransferEntity();
		int flag = UserConstants.PARAM_ERROR;
		try {
			String mobile = request.getParameter("mobile");
			
			String password = request.getParameter("password");
			
			String companyId = request.getParameter("companyId");
			
			SelectUserInput selectUserInput = new SelectUserInput();
			
			selectUserInput.setMobile(mobile);
			
			selectUserInput.setCompanyId(Integer.parseInt(companyId));
			
			selectUserInput.setPassword(StringUtil.md5Encrypt(password, "UTF-8"));
			
			flag = userService.isRegist(selectUserInput);
			switch (flag) {
			case UserConstants.SUCCESS:// 账号已注册
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.register"));
				baseTransferEntity.setData(mobile);
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.register"));
				break;
			case UserConstants.USER_NOT_EXIST:// 用户可以注册
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.exsit"));
				baseTransferEntity.setData("");
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.exsit"));
				break;
			case UserConstants.USR_EXCEPTIONS:// 参数异常
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.param"));
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.param"));
				break;
			case UserConstants.ISNOT_PHONE:
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.format"));
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.format"));
				break;

			}
		} catch (Exception e) {
			log.error("UserInfoController login--------->" + e.getMessage(), e);
			baseTransferEntity.setResultcode(MobileConfig
					.getStringCode("code.global.error.exception"));
			baseTransferEntity.setDesc("系统接口异常，请联系管理员！");
			baseTransferEntity.setData(null);
		}
		return baseTransferEntity;

	}

	/**
	 * 用户注册
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/service/handleCreateUser")
	@ResponseBody
	public BaseTransferEntity handleCreateUser(HttpServletRequest request,
			HttpServletResponse response) {
		BaseTransferEntity baseTransferEntity = new BaseTransferEntity();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		int flag = UserConstants.PARAM_ERROR;

		try {
			String mobile = request.getParameter("mobile");
			String roleId = request.getParameter("roleId");
			String companyId = request.getParameter("companyId");
			String organizationId = request.getParameter("organizationId");
			String name = request.getParameter("name");
			//TODO
			String password = request.getParameter("password");
			
			String md5NewPasswd = StringUtil.md5Encrypt(password, "UTF-8");
			
			SelectUserInput selectUserInput = new SelectUserInput();
			
			selectUserInput.setMobile(mobile);
			
			selectUserInput.setCompanyId(Integer.parseInt(companyId));
			
			selectUserInput.setRoleId(Integer.parseInt(roleId));
			
			selectUserInput.setOrganizationId(Integer.parseInt(organizationId));
			
			selectUserInput.setName(name);
			
			selectUserInput.setApprove(2);
			
			selectUserInput.setProcessId(0);
			
			selectUserInput.setDefectId(0);
			
			selectUserInput.setProductTeamId(0);
			
			selectUserInput.setPassword(md5NewPasswd);
			
			selectUserInput.setApTime(sdf.format(new Date()));
			
			flag = userService.handleCreateUser(selectUserInput);
			switch (flag) {
			case UserConstants.SUCCESS:// 注册成功
				// 获取session中的user
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.success"));
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.success"));
				break;
			case UserConstants.MOBILE_EXIST:// 账号存在
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.register"));
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.register"));
				break;
			case UserConstants.FORMAT_ERROR:// 格式错误
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.param"));
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.param"));
				break;
			case UserConstants.CODE_ERROR:// 验证错误
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.identity"));
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.identity"));
				break;
			case UserConstants.CODE_EXPIRE:// 验证码过期
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.identity"));
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.identity"));
				break;
			case UserConstants.PARAM_ERROR:// 入参错误
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.param"));
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.param"));
				break;
			case UserConstants.ISNOTREGIT:// 用户暂时无法注册
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.isnotregit"));
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.isnotregit"));
				break;
			}
		} catch (Exception e) {
			log.error("UserInfoController login--------->" + e.getMessage(), e);
			baseTransferEntity.setResultcode(MobileConfig
					.getStringCode("code.global.error.exception"));
			baseTransferEntity.setDesc("系统接口异常，请联系管理员！");
			baseTransferEntity.setData(null);
			// return new ResultObject(Constant.EXCEPTIONS, "系统接口异常，请联系管理员！",
			// null);
		}
		return baseTransferEntity;

	}

	/**
	 * 用户登录
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/service/handleUserLogin")
	@ResponseBody
	public BaseTransferEntity handleUserLogin(HttpServletRequest request,
			HttpServletResponse response) {
		BaseTransferEntity baseTransferEntity = new BaseTransferEntity();
		Map map = new HashMap();
		//电话号码
		String mobile = request.getParameter("mobile");
		//公司ID
		String companyId = request.getParameter("companyId");
		String organizationId = request.getParameter("organizationId");
		
		String password = request.getParameter("password");
		
		String md5NewPasswd = "" ;
		
		int flag = UserConstants.ERROR;
		
//		设备ID
//		String deviceId = request.getParameter("deviceId");
//		设备类型
//		String deviceType = request.getParameter("deviceType");
//		 int flag = UserConstants.PARAM_ERROR;
		try {
			if(!StringUtil.isEmpty(password)){
				
				md5NewPasswd = StringUtil.md5Encrypt(password, "UTF-8");
				
				map = userService.handleUserLogin(mobile, Integer.parseInt(companyId),md5NewPasswd);
				
				flag = Integer.parseInt(map.get("reason").toString());
			}else {
				
				flag = UserConstants.PARAM_ERROR;
			}
			//查询表bl_user，如果返回值为空，则
//			map = userService.handleUserLogin(mobile, Integer.parseInt(companyId));
		
			List<Map<String,Object>> lst = new ArrayList<Map<String,Object>>();
			
			lst.add(map);
			if (flag == UserConstants.SUCCESS) {// 登陆成功
				
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.success"));
				baseTransferEntity.setData(lst);
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.success"));
			} else if (flag == UserConstants.PARAM_ERROR) {// 参数异常
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.param"));
				baseTransferEntity.setData("");
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.param"));
			} else if (flag == UserConstants.PASSWD_INVALID) {// 审批被驳回
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.login"));
				baseTransferEntity.setData("");
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.login"));
			} else if (flag == UserConstants.USER_NOT_EXIST) {// 用户未注册
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.idcardexit"));
				baseTransferEntity.setData("");
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.idcardexit"));
			} else if (flag == UserConstants.ISNOTREGIT) {// 待审核
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.frequency"));
				baseTransferEntity.setData("");
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.frequency"));
			} else if (flag == UserConstants.ERROR_OLDPASSWD) {// 用户未注册
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.isnotoldpaypasswd"));//密码错误
				baseTransferEntity.setData("");
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.isnotoldpaypasswd"));
			} else {
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.exsit"));
				baseTransferEntity.setData("");
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.exsit"));
			}

		} catch (Exception e) {
			log.error("UserInfoController login--------->" + e.getMessage(), e);
			baseTransferEntity.setResultcode(MobileConfig
					.getStringCode("code.global.error.exception"));
			baseTransferEntity.setDesc("系统接口异常，请联系管理员！");
			baseTransferEntity.setData("");
		}

		return baseTransferEntity;
	}
	
	/**
	 * 角色信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/service/getRole")
	@ResponseBody
	public BaseTransferEntity getRole(HttpServletRequest request,
			HttpServletResponse response) {
		BaseTransferEntity baseTransferEntity = new BaseTransferEntity();
		try {
			//获取参数
			
			List lis = userService.getRole();
			
			baseTransferEntity.setResultcode(MobileConfig
					.getStringCode("code.global.success"));
			baseTransferEntity.setData(lis);
			baseTransferEntity.setDesc(MobileConfig
					.get("msg.global.success"));
		} catch (Exception e) {
			log.error("UserInfoController login--------->" + e.getMessage(), e);
			baseTransferEntity.setResultcode(MobileConfig
					.getStringCode("code.global.error.exception"));
			baseTransferEntity.setDesc("系统接口异常，请联系管理员！");
			baseTransferEntity.setData("");
		}
		
		return baseTransferEntity;
	}


	/**
	 * 退出登录
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/service/exitLogin")
	@ResponseBody
	public BaseTransferEntity exitLogin(HttpServletRequest request,
			HttpServletResponse response) {
		BaseTransferEntity baseTransferEntity = new BaseTransferEntity();
		try {
			//获取参数
			String sessionid = request.getParameter("sessionid");
			if (StringUtils.isBlank(sessionid)) {
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.param"));
				baseTransferEntity.setData("");
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.param"));
				return baseTransferEntity;
				
			}
			
			baseTransferEntity.setResultcode(MobileConfig
					.getStringCode("code.global.success"));
			baseTransferEntity.setDesc(MobileConfig.get("msg.global.success"));
			ehcacheUtil.removeCacheByKey(sessionid);
		} catch (Exception e) {
			log.error("UserInfoController login--------->" + e.getMessage(), e);
			baseTransferEntity.setResultcode(MobileConfig
					.getStringCode("code.global.error.exception"));
			baseTransferEntity.setDesc("系统接口异常，请联系管理员！");
			baseTransferEntity.setData("");
		}
		
		return baseTransferEntity;
	}

	/**
	 * 创建表结构
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/service/insterOrganization")
	@ResponseBody
	public BaseTransferEntity insterOrganization(HttpServletRequest request,
			HttpServletResponse response) {
		BaseTransferEntity baseTransferEntity = new BaseTransferEntity();
		int flag = UserConstants.PARAM_ERROR;
		try {
			String dirname = request.getParameter("dirname");
			
			String dirnameLevel = request.getParameter("dirnameLevel");
			
			String principal = request.getParameter("principal");
			
			String fatherId = request.getParameter("fatherId");
			
			InsterOrganization  insterOrganization = new InsterOrganization();
			
			insterOrganization.setDirname(dirname);
			
			insterOrganization.setDirnameLevel(dirnameLevel);
			
			insterOrganization.setCreateTime(new Date());
			
			insterOrganization.setFatherId(fatherId);
			
			insterOrganization.setPrincipal(principal);
			
			userService.insertOrganization(insterOrganization);
			baseTransferEntity.setResultcode(MobileConfig
					.getStringCode("code.global.success"));
			baseTransferEntity.setData("");
			baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.success"));
		} catch (Exception e) {
			log.error("UserInfoController login--------->" + e.getMessage(), e);
			baseTransferEntity.setResultcode(MobileConfig
					.getStringCode("code.global.error.exception"));
			baseTransferEntity.setDesc("系统接口异常，请联系管理员！");
			baseTransferEntity.setData(null);
		}
		return baseTransferEntity;

	}
	
	/**
	 * 创建表结构
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/service/selectOrganization")
	@ResponseBody
	public BaseTransferEntity selectOrganization(HttpServletRequest request,
			HttpServletResponse response) {
		BaseTransferEntity baseTransferEntity = new BaseTransferEntity();
		int flag = UserConstants.PARAM_ERROR;
		try {
			
			List lst = userService.selectOrganization();
			
			if(lst != null && lst.size() > 0){
				
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.success"));
				baseTransferEntity.setData("");
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.success"));
				
			}else{
				
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.param"));
				baseTransferEntity.setData("");
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.param"));
				
			}
		} catch (Exception e) {
			log.error("UserInfoController login--------->" + e.getMessage(), e);
			baseTransferEntity.setResultcode(MobileConfig
					.getStringCode("code.global.error.exception"));
			baseTransferEntity.setDesc("系统接口异常，请联系管理员！");
			baseTransferEntity.setData(null);
		}
		return baseTransferEntity;

	}
	/**
	 * 使用mobile与姓名查询人员
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/service/getUserByMobileAndName")
	@ResponseBody
	public BaseTransferEntity getUserByMobileAndName(HttpServletRequest request,
			HttpServletResponse response) {
		BaseTransferEntity baseTransferEntity = new BaseTransferEntity();
		int flag = UserConstants.PARAM_ERROR;
		try {

			String mobile = request.getParameter("mobile");
			
			String realName = request.getParameter("realName");
			
			SelectUserInput selectUserInput = new SelectUserInput();
			
			selectUserInput.setMobile(mobile);
			
			selectUserInput.setName(realName);
			
			List lst = userService.getUserByMobileAndName(selectUserInput);
			
			baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.success"));
			baseTransferEntity.setData(lst);
			baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.success"));
		} catch (Exception e) {
			log.error("UserInfoController login--------->" + e.getMessage(), e);
			baseTransferEntity.setResultcode(MobileConfig
					.getStringCode("code.global.error.exception"));
			baseTransferEntity.setDesc("系统接口异常，请联系管理员！");
			baseTransferEntity.setData(null);
		}
		return baseTransferEntity;
		
	}
	
	/**
	 * 查询所有企业领导信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/service/getUserByRoleType")
	@ResponseBody
	public BaseTransferEntity getUserByRoleType(HttpServletRequest request,
			HttpServletResponse response) {
		BaseTransferEntity baseTransferEntity = new BaseTransferEntity();
		try {

			SelectUserInput selectUserInput = new SelectUserInput();
			
			selectUserInput.setRoleType("L");
			
			List lst = userService.getUserByRoleType(selectUserInput);
			
			if(lst != null && lst.size() > 0){
				
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.success"));
				baseTransferEntity.setData(lst);
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.success"));
				
			}else{
				
				baseTransferEntity.setResultcode(MobileConfig
						.getStringCode("code.global.error.param"));
				baseTransferEntity.setData("");
				baseTransferEntity.setDesc(MobileConfig
						.get("msg.global.error.param"));
				
			}
		} catch (Exception e) {
			log.error("UserInfoController login--------->" + e.getMessage(), e);
			baseTransferEntity.setResultcode(MobileConfig
					.getStringCode("code.global.error.exception"));
			baseTransferEntity.setDesc("系统接口异常，请联系管理员！");
			baseTransferEntity.setData(null);
		}
		return baseTransferEntity;
		
	}
}
